package com.jinyou.web.interceptor;

import com.jinyou.utils.common.ValidateUtil;
import com.jinyou.utils.common.localthread.LocalRequestLangUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取请求参数中的lang语言
 */
public class ReqLangInterceptorAdapter extends HandlerInterceptorAdapter {

    private final static String REQ_LANG_KEY = "lang";

    private final Logger log = LoggerFactory.getLogger(ReqLangInterceptorAdapter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String lang = getRequestLang(request);
        if (ValidateUtil.isNotNull(lang)) {
            LocalRequestLangUtils.setLocalRequestLang(lang);
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        try {
            LocalRequestLangUtils.remove();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        super.afterCompletion(request, response, handler, ex);
    }

    // get lang
    private String getRequestLang(HttpServletRequest httpRequest) {
        String lang = httpRequest.getHeader(REQ_LANG_KEY);
        if (StringUtils.isBlank(lang)) {
            lang = httpRequest.getParameter(REQ_LANG_KEY);
        }
        return lang;
    }


}
